<template>
  <view class="address-edit-page">
    <view class="header">
      <view class="back" @click="goBack">
        <!-- 使用 Font Awesome 图标替代 uni-icons -->
        <i class="fa-solid fa-arrow-left"></i>
      </view>
      <view class="title">{{isEdit? '编辑收货地址' : '新建收货地址'}}</view>
      <view class="save-btn" @click="saveAddress">保存</view>
    </view>

    <view class="form-card">
      <view class="form-item">
        <view class="label">所在城市:</view>
        <picker :range="cities" v-model="addressForm.cityIndex" @change="onCityChange">
          <view class="picker">
            {{ cities[addressForm.cityIndex] || '请选择城市' }}
          </view>
        </picker>
      </view>

      <view class="form-item">
        <view class="label">小区/大厦/学校:</view>
        <input type="text" class="shuru" v-model="addressForm.department" placeholder="如北京大学" />
      </view>

      <view class="form-item">
        <view class="label">楼号-门牌号:</view>
        <input type="text" class="shuru" v-model="addressForm.houseNumber" placeholder="如A号楼B层" />
      </view>

      <view class="form-item">
        <view class="label">收货人:</view>
        <input type="text" class="shuru" v-model="addressForm.name" placeholder="请填写收货人的姓名" />
      </view>

      <view class="form-item">
        <view class="label">联系电话:</view>
        <input type="text" class="shuru" v-model="addressForm.phone" placeholder="请填写收货手机号" />
      </view>
    </view>
  </view>
</template>

<script>
	import config from '@/config'
export default {
  data() {
    return {
      isEdit: false,
      addressForm: {
        id: '',
        cityIndex: 0, // 新增城市索引
        city: '',
        department: '',
        houseNumber: '',
        name: '',
        phone: '',
        createdAt: '',
        updatedAt: ''
      },
      cities: [
        "北京市",
        "上海市",
        "广州市",
        "深圳市",
        "成都市",
        "杭州市",
        "武汉市",
        "重庆市",
        "南京市",
        "西安市",
        "长沙市",
        "郑州市",
        "苏州市",
        "天津市",
        "昆明市",
        "南昌市",
        "南宁市",
        "哈尔滨市",
        "贵阳市",
        "海口市",
        "洛阳市",
        "开封市",
      ]
    };
  },
  onLoad(options) {
    if (options.address) {
      this.isEdit = true;
      const address = JSON.parse(decodeURIComponent(options.address));
      this.addressForm = { ...address };
      // 设置城市索引
      const cityIndex = this.cities.indexOf(this.addressForm.city);
      this.addressForm.cityIndex = cityIndex > -1? cityIndex : 0;
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    onCityChange(e) {
      this.addressForm.cityIndex = e.detail.value;
      this.addressForm.city = this.cities[e.detail.value];
    },
    validateForm() {
      if (!this.addressForm.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        });
        return false;
      }
      if (!this.addressForm.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        });
        return false;
      }
      if (!this.addressForm.city) {
        uni.showToast({
          title: '请选择所在城市',
          icon: 'none'
        });
        return false;
      }
      if (!this.addressForm.department) {
        uni.showToast({
          title: '请输入小区/大厦名称',
          icon: 'none'
        });
        return false;
      }
      if (!this.addressForm.houseNumber) {
        uni.showToast({
          title: '请输入楼号/门牌号',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
    async saveAddress() {
      if (!this.validateForm()) return;

      try {
        const now = new Date().toISOString();

        if (this.isEdit) {
          // 编辑模式：更新现有地址
          const updateResponse = await uni.request({
            url: config.API+`/address/${this.addressForm.id}`,
            method: 'PUT',
            data: {
             ...this.addressForm,
              updatedAt: now
            }
          });

          if (updateResponse.statusCode === 200) {
            uni.showToast({
              title: '修改成功',
              icon:'success'
            });
          } else {
            throw new Error('保存失败');
          }
        } else {
          // 新建模式：添加新地址
          const newAddress = {
           ...this.addressForm,
            id: Date.now().toString(),
            createdAt: now,
            updatedAt: now
          };

          const createResponse = await uni.request({
            url: config.API+'/address',
            method: 'POST',
            data: newAddress
          });

          if (createResponse.statusCode === 201) {
            uni.showToast({
              title: '添加成功',
              icon:'success'
            });
          } else {
            throw new Error('保存失败');
          }
        }

        // 返回上一页并刷新地址列表
        setTimeout(() => {
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          if (prevPage && prevPage.$vm && prevPage.$vm.fetchAddresses) {
            prevPage.$vm.fetchAddresses();
          }
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败，请重试',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style>
.address-edit-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px; 
}

.header {
  width: 100%;
  max-width: 350px; 
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px; 
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px; 
}

.back {
  padding: 8px; 
}

.title {
  font-size: 20px; /* 进一步减小标题字体大小 */
  font-weight: 500;
}

.save-btn {
  color: #333;
  font-size: 20px; /* 进一步减小保存按钮字体大小 */
}

.form-card {
  width: 100%;
  max-width: 350px; 
  background-color: #fff;
  padding: 10px 15px; 
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form-item {
  padding: 8px 0; /* 进一步减少内边距，降低小卡片高度 */
  border-bottom: 1px solid #eee;
}
.shuru{
  font-size: 15px; 
}

.label {
  color: #333;
  font-size: 18px; /* 进一步减小标签字体大小 */
  margin-bottom: 6px; /* 进一步减少外边距 */
}

input {
  width: 100%;
  font-size: 22px; /* 进一步减小输入框字体大小 */
  color: #666;
  padding: 6px 0; /* 进一步减少内边距 */
}

input::placeholder {
  color: #999;
}

.picker {
  width: 100%;
  padding: 6px 0;
  font-size: 15px; /* 修改城市字体大小为 15px */
  color: #666;
}
</style>